// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

const db = cloud.database()
//所有用户对文章点赞的集合
const user_zan_story = db.collection("user_zan_story")
//所有故事的集合
const tree_hole_story = db.collection("tree_hole_story")

// 云函数入口函数
//对故事点赞或者取消点赞
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  //需要操作的故事的id
  const { id, story } = event
  const result = await user_zan_story
    .where({ _openid: wxContext.OPENID })
    .get()

  //用户从未给任何故事点过赞
  if (result.data.length === 0) {
    await user_zan_story
      .add({data: { _openid:wxContext.OPENID,zanStory: [id] }})
      .then(_ => {
        //更新故事点赞的数量
        tree_hole_story
          .doc(id)
          .update({
            data: { count: story.count + 1 }
          })
      })
    //将该故事标识为已赞
    story.isLike = true
    story.count = story.count + 1
    return story
  }
  //用户给故事点过赞
  //该用户所有的点赞故事
  let storyArr = result.data[0].zanStory
  //判断该用户是否对此故事点过赞
  const index = storyArr.findIndex(item => item === id)
  //用户对该故事已点赞
  if (index !== -1) {
    //在该用户点赞故事中删除该故事
    storyArr.splice(index, 1)
    await user_zan_story
      .doc(result.data[0]._id)
      .update({
        data: { zanStory: storyArr }
      })
      .then(_ => {
        //更新故事点赞的数量
        tree_hole_story
          .doc(id)
          .update({
            data: { count: story.count - 1 }
          })
      })
    //将该故事标识为未赞和更新数量
    story.isLike = false
    story.count = story.count - 1
    return story
  }
  //如果用户未给该故事点赞
  storyArr.push(id)
  await user_zan_story
    .doc(result.data[0]._id)
    .update({
      data: { zanStory: storyArr }
    })
    .then(_ => {
      // 更新点赞数量和是否点赞标识
      tree_hole_story
        .doc(id)
        .update({
          data: { count: story.count + 1 }
        })
    })
    //将该故事标识为已赞和更新数量
    story.isLike = true
    story.count = story.count + 1
    return story
}